package book.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

public abstract class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            String action = req.getParameter("action");

            Method method = this.getClass().getMethod(
                    action,
                    HttpServletRequest.class,
                    HttpServletResponse.class
            );
            method.invoke(this, req, resp);

        } catch (NoSuchMethodException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "请求的操作不存在");
        } catch (Exception e) {
            throw new ServletException("控制器处理错误", e);
        }
    }
}